package HTTP

import (
	"SQL/FSDB"
	"net/http"
)

func sendMessage(w http.ResponseWriter, req *http.Request) {

	var resCode = http.StatusOK
	var msg = ""
	var res interface{}
	defer func() {
		writeResult(w, resCode, msg, res)
	}()

	userID := req.FormValue("userID")
	talkerID := req.FormValue("talkerID")
	msgContent := req.FormValue("msgContent")

	ok := false
	if ok, resCode, msg = isArgsEmpty(userID, talkerID, msgContent); ok {
		return
	}
	if ok, resCode, msg = isValidID(userID, "UserID"); !ok {
		return
	}
	if ok, resCode, msg = isValidID(talkerID, "TalkerID"); !ok {
		return
	}
	if ok, resCode, msg = isValidMsgContent(msgContent); !ok {
		return
	}

	errCode, errMsg := sendMsgToDB(userID, talkerID, msgContent)
	msg = errMsg
	if errCode != Success {
		resCode = errCode
		return
	}
}

func sendMsgToDB(userID string, talkerID string, msg string) (errCode int, errMsg string) {

	sendMsgSQL := `INSERT INTO messages (sender,receiver,content) 
					VALUES ($1,$2,$3);`
	_, err := FSDB.Exec(sendMsgSQL, userID, talkerID, msg)
	if err != nil {
		return errDBExecFailed, err.Error()
	}
	return Success, "消息发送成功！"
}
